home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Aminet 1 (Walnut Creek)
/
Aminet - June 1993 [Walnut Creek].iso
/
usenet
/
sources
/
volume89
/
unix
/
gnused.1
< prev
next >
Wrap
Text File
|
1989-07-12
|
48KB
|
1,522 lines
Path: xanth!ames!apple!sun-barr!newstop!sun!swap!page
From: page%swap@Sun.COM (Bob Page)
Newsgroups: comp.sources.amiga
Subject: v89i165: gnused - gnu stream/script editor, Part01/03
Message-ID: <115134@sun.Eng.Sun.COM>
Date: 12 Jul 89 23:12:55 GMT
Sender: news@sun.Eng.Sun.COM
Lines: 1511
Approved: page@sun.com
Submitted-by: ehoogerbeets@rose.waterloo.edu (Edwin Hoogerbeets)
Posting-number: Volume 89, Issue 165
Archive-name: unix/gnused.1
The gnu stream/script editor.
[Oops. Binaries group says "Part01/03" but there's only one part. ..bob]
# This is a shell archive.
# Remove anything above and including the cut line.
# Then run the rest of the file through 'sh'.
# Unpacked files will be owned by you and have default permissions.
#----cut here-----cut here-----cut here-----cut here----#
#!/bin/sh
# shar: SHell ARchive
# Run the following text through 'sh' to create:
# README
# README.amiga
# alloca.c
# dir.c
# dir.h
# getopt.c
# glob.c
# This is archive 1 of a 3-part kit.
# This archive created: Wed Jul 12 15:53:23 1989
echo "extracting README"
sed 's/^X//' << \SHAR_EOF > README
XThis is the 'new, improvevd' GNU sed. Please report all bugs, comments,
Xrequests for features, etc to hack@gnu.ai.mit.edu or hack@wheaties.ai.mit.edu
Xor hack@media-lab.media.mit.edu or hack@lsrhs.UUCP (ONE of them should work.)
X
XTo compile sed, use something on the order of
Xcc -g -I. -o sed sed.c regex.c glob.c
SHAR_EOF
echo "extracting README.amiga"
sed 's/^X//' << \SHAR_EOF > README.amiga
XChanges made for the Amiga version:
X
X - added in definitions for memset, memcpy
X - added in correct include files
X - included alloca and getopt distributed with GnuGrep
X - wrote BSD-like opendir, readdir, and closedir for the Amiga
X (see dir.c, dir.h)
X - wrote memchr, and rewrote memmove and panic
X
XIf a memory exhausted error occurs, don't worry. (Be happy.)
XThis version of sed uses the Manx heapmem routines. These routines
Xpre-allocate a fixed size chunk of memory to deal out in the
Xindividual malloc and realloc calls. If you want to increase the
Xsize of this chunk, there is a global variable called _Heapsize,
Xwhich is set in main() in sed.c. Currently, it is set at 80K.
XYou may change it to be bigger (or smaller), but I found that
X80K was about right. This means, of course, that GnuSed requires
X120-150K of memory or so to run, with the 80K being a contiguous block.
X
XThis is still GNU code, and as such, it conforms to the GNU
Xpublic license. (see the comment at the beginning of grep.c)
XAny problems with the Amiga version, please send them to me at:
X
XEdwin Hoogerbeets
XUsenet: ehoogerbeets@rose.waterloo.edu (watmath!watrose!ehoogerbeets) or
X edwin@watcsc.waterloo.edu
XCIS: 72647,3675 (any time at all)
X
X
XSend any problems inherent in the source to:
X
Xhack@wheaties.ai.mit.edu
X
SHAR_EOF
echo "extracting alloca.c"
sed 's/^X//' << \SHAR_EOF > alloca.c
X/*
X alloca -- (mostly) portable public-domain implementation -- D A Gwyn
X
X This implementation of the PWB library alloca() function,
X which is used to allocate space off the run-time stack so
X that it is automatically reclaimed upon procedure exit,
X was inspired by discussions with J. Q. Johnson of Cornell.
X
X It should work under any C implementation that uses an
X actual procedure stack (as opposed to a linked list of
X frames). There are some preprocessor constants that can
X be defined when compiling for your specific system, for
X improved efficiency; however, the defaults should be okay.
X
X The general concept of this implementation is to keep
X track of all alloca()-allocated blocks, and reclaim any
X that are found to be deeper in the stack than the current
X invocation. This heuristic does not reclaim storage as
X soon as it becomes invalid, but it will do so eventually.
X
X As a special case, alloca(0) reclaims storage without
X allocating any. It is a good idea to use alloca(0) in
X your main control loop, etc. to force garbage collection.
X*/
X#ifndef lint
Xstatic char SCCSid[] = "@(#)alloca.c 1.1"; /* for the "what" utility */
X#endif
X
X#ifdef emacs
X#include "config.h"
X#ifdef static
X/* actually, only want this if static is defined as ""
X -- this is for usg, in which emacs must undefine static
X in order to make unexec workable
X */
X#ifndef STACK_DIRECTION
Xyou
Xlose
X-- must know STACK_DIRECTION at compile-time
X#endif /* STACK_DIRECTION undefined */
X#endif static
X#endif emacs
X
X#ifdef X3J11
Xtypedef void *pointer; /* generic pointer type */
X#else
Xtypedef char *pointer; /* generic pointer type */
X#endif
X
X#define NULL 0 /* null pointer constant */
X
Xextern void free();
Xextern pointer malloc();
X
X#ifdef AMIGA
X#define STACK_DIRECTION -1
X#endif
X
X/*
X Define STACK_DIRECTION if you know the direction of stack
X growth for your system; otherwise it will be automatically
X deduced at run-time.
X
X STACK_DIRECTION > 0 => grows toward higher addresses
X STACK_DIRECTION < 0 => grows toward lower addresses
X STACK_DIRECTION = 0 => direction of growth unknown
X*/
X
X#ifndef STACK_DIRECTION
X#define STACK_DIRECTION 0 /* direction unknown */
X#endif
X
X#if STACK_DIRECTION != 0
X
X#define STACK_DIR STACK_DIRECTION /* known at compile-time */
X
X#else /* STACK_DIRECTION == 0; need run-time code */
X
Xstatic int stack_dir; /* 1 or -1 once known */
X#define STACK_DIR stack_dir
X
Xstatic void
Xfind_stack_direction (/* void */)
X{
X static char *addr = NULL; /* address of first
X `dummy', once known */
X auto char dummy; /* to get stack address */
X
X if (addr == NULL)
X { /* initial entry */
X addr = &dummy;
X
X find_stack_direction (); /* recurse once */
X }
X else /* second entry */
X if (&dummy > addr)
X stack_dir = 1; /* stack grew upward */
X else
X stack_dir = -1; /* stack grew downward */
X}
X
X#endif /* STACK_DIRECTION == 0 */
X
X/*
X An "alloca header" is used to:
X (a) chain together all alloca()ed blocks;
X (b) keep track of stack depth.
X
X It is very important that sizeof(header) agree with malloc()
X alignment chunk size. The following default should work okay.
X*/
X
X#ifndef ALIGN_SIZE
X#define ALIGN_SIZE sizeof(double)
X#endif
X
Xtypedef union hdr
X{
X char align[ALIGN_SIZE]; /* to force sizeof(header) */
X struct
X {
X union hdr *next; /* for chaining headers */
X char *deep; /* for stack depth measure */
X } h;
X} header;
X
X/*
X alloca( size ) returns a pointer to at least `size' bytes of
X storage which will be automatically reclaimed upon exit from
X the procedure that called alloca(). Originally, this space
X was supposed to be taken from the current stack frame of the
X caller, but that method cannot be made to work for some
X implementations of C, for example under Gould's UTX/32.
X*/
X
Xstatic header *last_alloca_header = NULL; /* -> last alloca header */
X
Xpointer
Xalloca (size) /* returns pointer to storage */
X unsigned size; /* # bytes to allocate */
X{
X auto char probe; /* probes stack depth: */
X register char *depth = &probe;
X
X#if STACK_DIRECTION == 0
X if (STACK_DIR == 0) /* unknown growth direction */
X find_stack_direction ();
X#endif
X
X /* Reclaim garbage, defined as all alloca()ed storage that
X was allocated from deeper in the stack than currently. */
X
X {
X register header *hp; /* traverses linked list */
X
X for (hp = last_alloca_header; hp != NULL;)
X if (STACK_DIR > 0 && hp->h.deep > depth
X || STACK_DIR < 0 && hp->h.deep < depth)
X {
X register header *np = hp->h.next;
X
X free ((pointer) hp); /* collect garbage */
X
X hp = np; /* -> next header */
X }
X else
X break; /* rest are not deeper */
X
X last_alloca_header = hp; /* -> last valid storage */
X }
X
X if (size == 0)
X return NULL; /* no allocation required */
X
X /* Allocate combined header + user data storage. */
X
X {
X register pointer new = malloc (sizeof (header) + size);
X /* address of header */
X
X ((header *)new)->h.next = last_alloca_header;
X ((header *)new)->h.deep = depth;
X
X last_alloca_header = (header *)new;
X
X /* User storage begins just after header. */
X
X return (pointer)((char *)new + sizeof(header));
X }
X}
SHAR_EOF
echo "extracting dir.c"
sed 's/^X//' << \SHAR_EOF > dir.c
X/*
X *
X * BSD-like directory searching routines
X * Edwin Hoogerbeets 1989
X *
X */
X#ifdef AMIGA
X#include <stdio.h>
X#include "dir.h"
X#include <exec/memory.h>
X
Xextern char *malloc();
Xextern char *free();
Xextern struct FileLock *Lock();
Xextern char *AllocMem();
X
Xstatic struct direct direntry;
X
X#define FIBSIZE (long)sizeof(struct FileInfoBlock)
X
XDIR *opendir(filename)
Xchar *filename;
X{
X DIR *dir;
X
X if ( !(dir = (DIR *) malloc(sizeof(DIR))) ) {
X return(NULL);
X }
X
X /* needs to be long word aligned, so AllocMem must be used */
X if ( !(dir->fib = (struct FileInfoBlock *)
X AllocMem(FIBSIZE,MEMF_CLEAR)) ) {
X free(dir);
X return(NULL);
X }
X
X if ( !(dir->lock = Lock(filename,ACCESS_READ)) ) {
X FreeMem(dir->fib,FIBSIZE);
X free(dir);
X return(NULL);
X }
X
X Examine(dir->lock,dir->fib);
X strncpy(dir->name,filename,31L);
X
X return(dir);
X}
X
Xstruct direct *readdir(dir)
XDIR *dir;
X{
X if ( dir ) {
X if ( ExNext(dir->lock,dir->fib) ) {
X strcpy(direntry.d_name,dir->fib->fib_FileName);
X direntry.d_namlen = strlen(direntry.d_name);
X
X /* inode number emulation! */
X direntry.d_ino = dir->fib->fib_DiskKey;
X
X direntry.d_reclen = sizeof(struct direct) - MAXNAMELEN +
X direntry.d_namlen + 1;
X
X return(&direntry);
X } else {
X return(NULL);
X }
X } else {
X return(NULL);
X }
X}
X
Xvoid closedir(dir)
XDIR *dir;
X{
X if ( dir ) {
X UnLock(dir->lock);
X FreeMem(dir->fib,FIBSIZE);
X free(dir);
X }
X}
X
X#endif /* AMIGA */
SHAR_EOF
echo "extracting dir.h"
sed 's/^X//' << \SHAR_EOF > dir.h
X/*
X *
X * BSD-like directory searching for Manx C
X * Edwin Hoogerbeets 1989
X *
X */
X
X#include <libraries/dosextens.h>
X
X#define MAXNAMELEN 31
X
Xstruct direct {
X ULONG d_ino;
X USHORT d_reclen;
X USHORT d_namlen;
X char d_name[MAXNAMELEN + 1];
X};
X
X#if 0
Xtypedef struct FileInfoBlock
X dirent;
X
X#define d_name fib_FileName
X
X#endif
X
Xtypedef struct DIR {
X struct FileLock *lock; /* lock on the directory */
X char name[MAXNAMELEN+1]; /* name of the directory */
X struct FileInfoBlock *fib; /* pointer to temporary space for searching */
X long loc; /* current location of the search */
X} DIR;
X
Xextern DIR *opendir();
Xextern struct direct *readdir();
Xextern void closedir();
X
X
X
SHAR_EOF
echo "extracting getopt.c"
sed 's/^X//' << \SHAR_EOF > getopt.c
X/* Getopt for GNU.
X Copyright (C) 1987 Free Software Foundation, Inc.
X
X NO WARRANTY
X
X BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
XNO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT
XWHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
XRICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
XWITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
XBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
XFITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY
XAND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
XDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
XCORRECTION.
X
X IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
XSTALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
XWHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
XLIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
XOTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
XUSE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
XDATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
XA FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
XPROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
XDAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
X
X GENERAL PUBLIC LICENSE TO COPY
X
X 1. You may copy and distribute verbatim copies of this source file
Xas you receive it, in any medium, provided that you conspicuously and
Xappropriately publish on each copy a valid copyright notice "Copyright
X (C) 1987 Free Software Foundation, Inc."; and include following the
Xcopyright notice a verbatim copy of the above disclaimer of warranty
Xand of this License. You may charge a distribution fee for the
Xphysical act of transferring a copy.
X
X 2. You may modify your copy or copies of this source file or
Xany portion of it, and copy and distribute such modifications under
Xthe terms of Paragraph 1 above, provided that you also do the following:
X
X a) cause the modified files to carry prominent notices stating
X that you changed the files and the date of any change; and
X
X b) cause the whole of any work that you distribute or publish,
X that in whole or in part contains or is a derivative of this
X program or any part thereof, to be licensed at no charge to all
X third parties on terms identical to those contained in this
X License Agreement (except that you may choose to grant more
X extensive warranty protection to third parties, at your option).
X
X c) You may charge a distribution fee for the physical act of
X transferring a copy, and you may at your option offer warranty
X protection in exchange for a fee.
X
X 3. You may copy and distribute this program or any portion of it in
Xcompiled, executable or object code form under the terms of Paragraphs
X1 and 2 above provided that you do the following:
X
X a) cause each such copy to be accompanied by the
X corresponding machine-readable source code, which must
X be distributed under the terms of Paragraphs 1 and 2 above; or,
X
X b) cause each such copy to be accompanied by a
X written offer, with no time limit, to give any third party
X free (except for a nominal shipping charge) a machine readable
X copy of the corresponding source code, to be distributed
X under the terms of Paragraphs 1 and 2 above; or,
X
X c) in the case of a recipient of this program in compiled, executable
X or object code form (without the corresponding source code) you
X shall cause copies you distribute to be accompanied by a copy
X of the written offer of source code which you received along
X with the copy you received.
X
X 4. You may not copy, sublicense, distribute or transfer this program
Xexcept as expressly provided under this License Agreement. Any attempt
Xotherwise to copy, sublicense, distribute or transfer this program is void and
Xyour rights to use the program under this License agreement shall be
Xautomatically terminated. However, parties who have received computer
Xsoftware programs from you with this License Agreement will not have
Xtheir licenses terminated so long as such parties remain in full compliance.
X
X 5. If you wish to incorporate parts of this program into other free
Xprograms whose distribution conditions are different, write to the Free
XSoftware Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet
Xworked out a simple rule that can be stated here, but we will often permit
Xthis. We will be guided by the two goals of preserving the free status of
Xall derivatives of our free software and of promoting the sharing and reuse of
Xsoftware.
X
X
XIn other words, you are welcome to use, share and improve this program.
XYou are forbidden to forbid anyone else to use, share and improve
Xwhat you give them. Help stamp out software-hoarding! */
X
X/* This version of `getopt' appears to the caller like standard Unix `getopt'
X but it behaves differently for the user, since it allows the user
X to intersperse the options with the other arguments.
X
X As `getopt' works, it permutes the elements of `argv' so that,
X when it is done, all the options precede everything else. Thus
X all application programs are extended to handle flexible argument order.
X
X Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
X Then the behavior is completely standard.
X
X GNU application programs can use a third alternative mode in which
X they can distinguish the relative order of options and other arguments. */
X
X#include <stdio.h>
X
X#ifdef sparc
X#include <alloca.h>
X#endif
X#ifdef USG
X#define bcopy(s, d, l) memcpy((d), (s), (l))
X#endif
X
X#ifdef AZTEC_C
X#define memcpy(dst,src,n) movmem((src),(dst),(n))
X#define memset(src,value,howmany) setmem((src),(howmany),(value))
X#define bcopy(src,dst,n) movmem((src),(dst),(n))
X#endif
X
X/* For communication from `getopt' to the caller.
X When `getopt' finds an option that takes an argument,
X the argument value is returned here.
X Also, when `ordering' is RETURN_IN_ORDER,
X each non-option ARGV-element is returned here. */
X
Xchar *optarg = 0;
X
X/* Index in ARGV of the next element to be scanned.
X This is used for communication to and from the caller
X and for communication between successive calls to `getopt'.
X
X On entry to `getopt', zero means this is the first call; initialize.
X
X When `getopt' returns EOF, this is the index of the first of the
X non-option elements that the caller should itself scan.
X
X Otherwise, `optind' communicates from one call to the next
X how much of ARGV has been scanned so far. */
X
Xint optind = 0;
X
X/* The next char to be scanned in the option-element
X in which the last option character we returned was found.
X This allows us to pick up the scan where we left off.
X
X If this is zero, or a null string, it means resume the scan
X by advancing to the next ARGV-element. */
X
Xstatic char *nextchar;
X
X/* Callers store zero here to inhibit the error message
X for unrecognized options. */
X
Xint opterr = 1;
X
X/* Describe how to deal with options that follow non-option ARGV-elements.
X
X UNSPECIFIED means the caller did not specify anything;
X the default is then REQUIRE_ORDER if the environment variable
X _OPTIONS_FIRST is defined, PERMUTE otherwise.
X
X REQUIRE_ORDER means don't recognize them as options.
X Stop option processing when the first non-option is seen.
X This is what Unix does.
X
X PERMUTE is the default. We permute the contents of `argv' as we scan,
X so that eventually all the options are at the end. This allows options
X to be given in any order, even with programs that were not written to
X expect this.
X
X RETURN_IN_ORDER is an option available to programs that were written
X to expect options and other ARGV-elements in any order and that care about
X the ordering of the two. We describe each non-option ARGV-element
X as if it were the argument of an option with character code zero.
X Using `-' as the first character of the list of option characters
X requests this mode of operation.
X
X The special argument `--' forces an end of option-scanning regardless
X of the value of `ordering'. In the case of RETURN_IN_ORDER, only
X `--' can cause `getopt' to return EOF with `optind' != ARGC. */
X
Xstatic enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
X
X/* Handle permutation of arguments. */
X
X/* Describe the part of ARGV that contains non-options that have
X been skipped. `first_nonopt' is the index in ARGV of the first of them;
X `last_nonopt' is the index after the last of them. */
X
Xstatic int first_nonopt;
Xstatic int last_nonopt;
X
X/* Exchange two adjacent subsequences of ARGV.
X One subsequence is elements [first_nonopt,last_nonopt)
X which contains all the non-options that have been skipped so far.
X The other is elements [last_nonopt,optind), which contains all
X the options processed since those non-options were skipped.
X
X `first_nonopt' and `last_nonopt' are relocated so that they describe
X the new indices of the non-options in ARGV after they are moved. */
X
Xstatic void
Xexchange (argv)
X char **argv;
X{
X int nonopts_size
X = (last_nonopt - first_nonopt) * sizeof (char *);
X char **temp = (char **) alloca (nonopts_size);
X
X /* Interchange the two blocks of data in argv. */
X
X bcopy (&argv[first_nonopt], temp, nonopts_size);
X bcopy (&argv[last_nonopt], &argv[first_nonopt],
X (optind - last_nonopt) * sizeof (char *));
X bcopy (temp, &argv[first_nonopt + optind - last_nonopt],
X nonopts_size);
X
X /* Update records for the slots the non-options now occupy. */
X
X first_nonopt += (optind - last_nonopt);
X last_nonopt = optind;
X}
X
X/* Scan elements of ARGV (whose length is ARGC) for option characters
X given in OPTSTRING.
X
X If an element of ARGV starts with '-', and is not exactly "-" or "--",
X then it is an option element. The characters of this element
X (aside from the initial '-') are option characters. If `getopt'
X is called repeatedly, it returns successively each of theoption characters
X from each of the option elements.
X
X If `getopt' finds another option character, it returns that character,
X updating `optind' and `nextchar' so that the next call to `getopt' can
X resume the scan with the following option character or ARGV-element.
X
X If there are no more option characters, `getopt' returns `EOF'.
X Then `optind' is the index in ARGV of the first ARGV-element
X that is not an option. (The ARGV-elements have been permuted
X so that those that are not options now come last.)
X
X OPTSTRING is a string containing the legitimate option characters.
X A colon in OPTSTRING means that the previous character is an option
X that wants an argument. The argument is taken from the rest of the
X current ARGV-element, or from the following ARGV-element,
X and returned in `optarg'.
X
X If an option character is seen that is not listed in OPTSTRING,
X return '?' after printing an error message. If you set `opterr' to
X zero, the error message is suppressed but we still return '?'.
X
X If a char in OPTSTRING is followed by a colon, that means it wants an arg,
X so the following text in the same ARGV-element, or the text of the following
X ARGV-element, is returned in `optarg. Two colons mean an option that
X wants an optional arg; if there is text in the current ARGV-element,
X it is returned in `optarg'.
X
X If OPTSTRING starts with `-', it requests a different method of handling the
X non-option ARGV-elements. See the comments about RETURN_IN_ORDER, above. */
X
Xint
Xgetopt (argc, argv, optstring)
X int argc;
X char **argv;
X char *optstring;
X{
X /* Initialize the internal data when the first call is made.
X Start processing options with ARGV-element 1 (since ARGV-element 0
X is the program name); the sequence of previously skipped
X non-option ARGV-elements is empty. */
X
X if (optind == 0)
X {
X first_nonopt = last_nonopt = optind = 1;
X
X nextchar = 0;
X
X /* Determine how to handle the ordering of options and nonoptions. */
X
X if (optstring[0] == '-')
X ordering = RETURN_IN_ORDER;
X else if (getenv ("_POSIX_OPTION_ORDER") != 0)
X ordering = REQUIRE_ORDER;
X else
X ordering = PERMUTE;
X }
X
X if (nextchar == 0 || *nextchar == 0)
X {
X if (ordering == PERMUTE)
X {
X /* If we have just processed some options following some non-options,
X exchange them so that the options come first. */
X
X if (first_nonopt != last_nonopt && last_nonopt != optind)
X exchange (argv);
X else if (last_nonopt != optind)
X first_nonopt = optind;
X
X /* Now skip any additional non-options
X and extend the range of non-options previously skipped. */
X
X while (optind < argc
X && (argv[optind][0] != '-'
X || argv[optind][1] == 0))
X optind++;
X last_nonopt = optind;
X }
X
X /* Special ARGV-element `--' means premature end of options.
X Skip it like a null option,
X then exchange with previous non-options as if it were an option,
X then skip everything else like a non-option. */
X
X if (optind != argc && !strcmp (argv[optind], "--"))
X {
X optind++;
X
X if (first_nonopt != last_nonopt && last_nonopt != optind)
X exchange (argv);
X else if (first_nonopt == last_nonopt)
X first_nonopt = optind;
X last_nonopt = argc;
X
X optind = argc;
X }
X
X /* If we have done all the ARGV-elements, stop the scan
X and back over any non-options that we skipped and permuted. */
X
X if (optind == argc)
X {
X /* Set the next-arg-index to point at the non-options
X that we previously skipped, so the caller will digest them. */
X if (first_nonopt != last_nonopt)
X optind = first_nonopt;
X return EOF;
X }
X
X /* If we have come to a non-option and did not permute it,
X either stop the scan or describe it to the caller and pass it by. */
X
X if (argv[optind][0] != '-' || argv[optind][1] == 0)
X {
X if (ordering == REQUIRE_ORDER)
X return EOF;
X optarg = argv[optind++];
X return 0;
X }
X
X /* We have found another option-ARGV-element.
X Start decoding its characters. */
X
X nextchar = argv[optind] + 1;
X }
X
X /* Look at and handle the next option-character. */
X
X {
X char c = *nextchar++;
X char *temp = (char *) index (optstring, c);
X
X /* Increment `optind' when we start to process its last character. */
X if (*nextchar == 0)
X optind++;
X
X if (temp == 0 || c == ':')
X {
X if (opterr != 0)
X {
X if (c < 040 || c >= 0177)
X fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
X argv[0], c);
X else
X fprintf (stderr, "%s: unrecognized option `-%c'\n",
X argv[0], c);
X }
X return '?';
X }
X if (temp[1] == ':')
X {
X if (temp[2] == ':')
X {
X /* This is an option that accepts an argument optionally. */
X if (*nextchar != 0)
X {
X optarg = nextchar;
X optind++;
X }
X else
X optarg = 0;
X nextchar = 0;
X }
X else
X {
X /* This is an option that requires an argument. */
X if (*nextchar != 0)
X {
X optarg = nextchar;
X /* If we end this ARGV-element by taking the rest as an arg,
X we must advance to the next element now. */
X optind++;
X }
X else if (optind == argc)
X {
X if (opterr != 0)
X fprintf (stderr, "%s: no argument for `-%c' option\n",
X argv[0], c);
X c = '?';
X }
X else
X /* We already incremented `optind' once;
X increment it again when taking next ARGV-elt as argument. */
X optarg = argv[optind++];
X nextchar = 0;
X }
X }
X return c;
X }
X}
X
X#ifdef TEST
X
X/* Compile with -DTEST to make an executable for use in testing
X the above definition of `getopt'. */
X
Xint
Xmain (argc, argv)
X int argc;
X char **argv;
X{
X char c;
X int digit_optind = 0;
X
X while (1)
X {
X int this_option_optind = optind;
X if ((c = getopt (argc, argv, "abc:d:0123456789")) == EOF)
X break;
X
X switch (c)
X {
X case '0':
X case '1':
X case '2':
X case '3':
X case '4':
X case '5':
X case '6':
X case '7':
X case '8':
X case '9':
X if (digit_optind != 0 && digit_optind != this_option_optind)
X printf ("digits occur in two different argv-elements.\n");
X digit_optind = this_option_optind;
X printf ("option %c\n", c);
X break;
X
X case 'a':
X printf ("option a\n");
X break;
X
X case 'b':
X printf ("option b\n");
X break;
X
X case 'c':
X printf ("option c with value `%s'\n", optarg);
X break;
X
X case '?':
X break;
X
X default:
X printf ("?? getopt returned character code 0%o ??\n", c);
X }
X }
X
X if (optind < argc)
X {
X printf ("non-option ARGV-elements: ");
X while (optind < argc)
X printf ("%s ", argv[optind++]);
X printf ("\n");
X }
X
X return 0;
X}
X
X#endif /* TEST */
SHAR_EOF
echo "extracting glob.c"
sed 's/^X//' << \SHAR_EOF > glob.c
X/* File-name wildcard pattern matching for GNU.
X Copyright (C) 1985, 1988 Free Software Foundation, Inc.
X
X NO WARRANTY
X
X BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
XNO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT
XWHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
XRICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
XWITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
XBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
XFITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY
XAND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
XDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
XCORRECTION.
X
X IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
XSTALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
XWHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
XLIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
XOTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
XUSE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
XDATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
XA FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
XPROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
XDAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
X
X GENERAL PUBLIC LICENSE TO COPY
X
X 1. You may copy and distribute verbatim copies of this source file
Xas you receive it, in any medium, provided that you conspicuously and
Xappropriately publish on each copy a valid copyright notice "Copyright
X(C) 1988 Free Software Foundation, Inc."; and include following the
Xcopyright notice a verbatim copy of the above disclaimer of warranty
Xand of this License.
X
X 2. You may modify your copy or copies of this source file or
Xany portion of it, and copy and distribute such modifications under
Xthe terms of Paragraph 1 above, provided that you also do the following:
X
X a) cause the modified files to carry prominent notices stating
X that you changed the files and the date of any change; and
X
X b) cause the whole of any work that you distribute or publish,
X that in whole or in part contains or is a derivative of this
X program or any part thereof, to be licensed at no charge to all
X third parties on terms identical to those contained in this
X License Agreement (except that you may choose to grant more extensive
X warranty protection to some or all third parties, at your option).
X
X c) You may charge a distribution fee for the physical act of
X transferring a copy, and you may at your option offer warranty
X protection in exchange for a fee.
X
XMere aggregation of another unrelated program with this program (or its
Xderivative) on a volume of a storage or distribution medium does not bring
Xthe other program under the scope of these terms.
X
X 3. You may copy and distribute this program (or a portion or derivative
Xof it, under Paragraph 2) in object code or executable form under the terms
Xof Paragraphs 1 and 2 above provided that you also do one of the following:
X
X a) accompany it with the complete corresponding machine-readable
X source code, which must be distributed under the terms of
X Paragraphs 1 and 2 above; or,
X
X b) accompany it with a written offer, valid for at least three
X years, to give any third party free (except for a nominal
X shipping charge) a complete machine-readable copy of the
X corresponding source code, to be distributed under the terms of
X Paragraphs 1 and 2 above; or,
X
X c) accompany it with the information you received as to where the
X corresponding source code may be obtained. (This alternative is
X allowed only for noncommercial distribution and only if you
X received the program in object code or executable form alone.)
X
XFor an executable file, complete source code means all the source code for
Xall modules it contains; but, as a special exception, it need not include
Xsource code for modules which are standard libraries that accompany the
Xoperating system on which the executable file runs.
X
X 4. You may not copy, sublicense, distribute or transfer this program
Xexcept as expressly provided under this License Agreement. Any attempt
Xotherwise to copy, sublicense, distribute or transfer this program is void and
Xyour rights to use the program under this License agreement shall be
Xautomatically terminated. However, parties who have received computer
Xsoftware programs from you with this License Agreement will not have
Xtheir licenses terminated so long as such parties remain in full compliance.
X
X
XIn other words, you are welcome to use, share and improve this program.
XYou are forbidden to forbid anyone else to use, share and improve
Xwhat you give them. Help stamp out software-hoarding! */
X
X
X/* To whomever it may concern: I have never seen the code which most
X Unix programs use to perform this function. I wrote this from scratch
X based on specifications for the pattern matching. */
X
X#ifdef AMIGA
X#include <exec/types.h>
X#else
X#include <sys/types.h>
X#endif
X
X#ifdef AMIGA
X#include "dir.h"
X#define DP_NAMELEN(x) (x)->d_namlen
X#endif
X
X#ifdef AZTEC_C
X#define bcopy(s, d, n) movmem((s),(d),(n))
X#endif
X
X#ifdef USG_OLD
X#include <ndir.h>
X#include <memory.h>
X#include <string.h>
X#define bcopy(s, d, n) ((void) memcpy ((d), (s), (n)))
X
Xextern char *memcpy ();
X
X#else /* not USG */
X
X#ifdef HPUX
X#include <sys/dir.h>
X#endif
X
X#ifdef USG
X#include <sys/dir.h>
X#include <dirent.h>
X#include <string.h>
X#define DP_NAMELEN(x) strlen ((x)->d_name)
X#define direct dirent
X#else
X
X#if unix
X#include <sys/dir.h>
X#include <strings.h>
Xextern void bcopy ();
X#endif /* unix */
X
X#endif /* USG */
X#endif /* USG_OLD */
X
X#ifndef DP_NAMELEN
X#define DP_NAMELEN(x) (x)->d_namlen
X#endif
X
X#ifdef sparc
X#include <alloca.h>
X#else
Xextern char *alloca ();
X#endif /* sparc */
X
Xextern char *malloc (), *realloc ();
Xextern void free ();
X
X#ifndef NULL
X#define NULL 0
X#endif
X
X
X#ifdef unix
X#define CURRENTDIR "."
X#endif
X
X#ifdef AMIGA
X#define CURRENTDIR ""
X#endif
X
X/* Global variable which controls whether or not * matches .files.
X Non-zero says no match. */
Xint noglob_dot_filenames = 1;
X
X
Xstatic int glob_match_after_star ();
X
X/* Return nonzero if PATTERN has any special globbing chars in it. */
Xint
Xglob_pattern_p (pattern)
X char *pattern;
X{
X register char *p = pattern;
X register char c;
X
X while ((c = *p++))
X {
X switch (c)
X {
X case '?':
X case '[':
X case '*':
X return 1;
X
X case '\\':
X if (*p++ == 0) return 0;
X default:
X ;
X }
X }
X
X return 0;
X}
X
X
X/* Match the pattern PATTERN against the string TEXT;
X return 1 if it matches, 0 otherwise.
X
X A match means the entire string TEXT is used up in matching.
X
X In the pattern string, `*' matches any sequence of characters,
X `?' matches any character, [SET] matches any character in the specified set,
X [^SET] matches any character not in the specified set.
X
X A set is composed of characters or ranges; a range looks like
X character hyphen character (as in 0-9 or A-Z).
X [0-9a-zA-Z_] is the set of characters allowed in C identifiers.
X Any other character in the pattern must be matched exactly.
X
X To suppress the special syntactic significance of any of `[]*?^-\',
X and match the character exactly, precede it with a `\'.
X
X If DOT_SPECIAL is nonzero,
X `*' and `?' do not match `.' at the beginning of TEXT. */
X
Xint
Xglob_match (pattern, text, dot_special)
X char *pattern, *text;
X int dot_special;
X{
X register char *p = pattern, *t = text;
X register char c;
X
X while ((c = *p++))
X {
X switch (c)
X {
X case '?':
X if (*t == 0 || (dot_special && t == text && *t == '.')) return 0;
X else ++t;
X break;
X
X case '\\':
X if (*p++ != *t++) return 0;
X break;
X
X case '*':
X if (dot_special && t == text && *t == '.')
X return 0;
X return glob_match_after_star (p, t);
X
X case '[':
X {
X register char c1 = *t++;
X register int invert = (*p == '^');
X
X if (invert) p++;
X
X c = *p++;
X while (1)
X {
X register char cstart = c, cend = c;
X
X if (c == '\\')
X {
X cstart = *p++; cend = cstart;
X }
X
X if (!c) return (0);
X
X c = *p++;
X
X if (c == '-')
X {
X cend = *p++;
X if (cend == '\\')
X cend = *p++;
X if (!cend) return (0);
X c = *p++;
X }
X if (c1 >= cstart && c1 <= cend) goto match;
X if (c == ']')
X break;
X }
X if (!invert) return 0;
X break;
X
X match:
X /* Skip the rest of the [...] construct that already matched. */
X while (c != ']')
X {
X if (!c || !(c = *p++)) return (0);
X if (c == '\\') p++;
X }
X if (invert) return 0;
X break;
X }
X
X default:
X if (c != *t++) return 0;
X }
X }
X
X if (*t) return 0;
X return 1;
X}
X
X/* Like glob_match, but match PATTERN against any final segment of TEXT. */
X
Xstatic int
Xglob_match_after_star (pattern, text)
X char *pattern, *text;
X{
X register char *p = pattern, *t = text;
X register char c, c1;
X
X while ((c = *p++) == '?' || c == '*')
X {
X if (c == '?' && *t++ == 0)
X return 0;
X }
X
X if (c == 0)
X return 1;
X
X if (c == '\\') c1 = *p;
X else c1 = c;
X
X for (;;)
X {
X if ((c == '[' || *t == c1)
X && glob_match (p - 1, t, 0))
X return 1;
X if (*t++ == 0) return 0;
X }
X}
X
X/* Return a vector of names of files in directory DIR
X whose names match glob pattern PAT.
X The names are not in any particular order.
X Wildcards at the beginning of PAT do not match an initial period.
X
X The vector is terminated by an element that is a null pointer.
X
X To free the space allocated, first free the vector's elements,
X then free the vector.
X
X Return 0 if cannot get enough memory to hold the pointer
X and the names.
X
X Return -1 if cannot access directory DIR.
X Look in errno for more information. */
X
Xchar **
Xglob_vector (pat, dir)
X char *pat;
X char *dir;
X{
X struct globval
X {
X struct globval *next;
X char *name;
X };
X
X DIR *d;
X register struct direct *dp;
X struct globval *lastlink;
X register struct globval *nextlink;
X register char *nextname;
X int count;
X int lose;
X register char **name_vector;
X register int i;
X
X if (!(d = opendir (dir)))
X return (char **) -1;
X
X lastlink = 0;
X count = 0;
X lose = 0;
X
X /* Scan the directory, finding all names that match.
X For each name that matches, allocate a struct globval
X on the stack and store the name in it.
X Chain those structs together; lastlink is the front of the chain. */
X /* Loop reading blocks */
X while (1)
X {
X dp = readdir (d);
X if (!dp) break;
X
X if (dp->d_ino && glob_match (pat, dp->d_name, noglob_dot_filenames))
X {
X nextlink = (struct globval *) alloca (sizeof (struct globval));
X nextlink->next = lastlink;
X nextname = (char *) malloc (DP_NAMELEN (dp) + 1);
X if (!nextname)
X {
X lose = 1;
X break;
X }
X lastlink = nextlink;
X nextlink->name = nextname;
X bcopy (dp->d_name, nextname, DP_NAMELEN(dp) + 1);
X count++;
X }
X }
X closedir (d);
X
X name_vector = (char **) malloc ((count + 1) * sizeof (char *));
X
X /* Have we run out of memory? */
X if (!name_vector || lose)
X {
X /* Here free the strings we have got */
X while (lastlink)
X {
X free (lastlink->name);
X lastlink = lastlink->next;
X }
X return 0;
X }
X
X /* Copy the name pointers from the linked list into the vector */
X for (i = 0; i < count; i++)
X {
X name_vector[i] = lastlink->name;
X lastlink = lastlink->next;
X }
X
X name_vector[count] = 0;
X return name_vector;
X}
X
X/* Return a new array which is the concatenation of each string in
X ARRAY to DIR. */
X
Xstatic char **
Xglob_dir_to_array (dir, array)
X char *dir, **array;
X{
X register int i, l;
X int add_slash = 0;
X char **result;
X
X l = strlen (dir);
X if (!l) return (array);
X
X if (dir[l - 1] != '/') add_slash++;
X
X for (i = 0; array[i]; i++);
X
X result = (char **)malloc ((1 + i) * sizeof (char *));
X if (!result) return (result);
X
X for (i = 0; array[i]; i++) {
X result[i] = (char *)malloc (1 + l + add_slash + strlen (array[i]));
X if (!result[i]) return (char **)NULL;
X strcpy (result[i], dir);
X if (add_slash) strcat (result[i], "/");
X strcat (result[i], array[i]);
X }
X result[i] = (char *)NULL;
X
X /* Free the input array. */
X for (i = 0; array[i]; i++) free (array[i]);
X free (array);
X return (result);
X}
X
X/* Do globbing on PATHNAME. Return an array of pathnames that match,
X marking the end of the array with a null-pointer as an element.
X If no pathnames match, then the array is empty (first element is null).
X If there isn't enough memory, then return NULL.
X If a file system error occurs, return -1; `errno' has the error code.
X
X Wildcards at the beginning of PAT, or following a slash,
X do not match an initial period. */
X
Xchar **
Xglob_filename (pathname)
X char *pathname;
X{
X char **result = (char **)malloc (1 * sizeof (char *));
X int i, result_size = 1;
X char *directory_name, *filename;
X
X if (result) result[0] = (char *)NULL;
X else return (result);
X
X /* Find the filename. */
X i = strlen (pathname) - 1;
X
Xlook_again:
X while (i > -1 && pathname[i] != '/') i--;
X if (i > 0 && pathname[i - 1] == '\\')
X {
X --i;
X goto look_again;
X }
X i++;
X
X filename = (char *)alloca (strlen (pathname) - i + 1);
X directory_name = (char *)alloca (i + 1);
X
X if (!filename || !directory_name)
X {
X memory_error:
X if (result)
X {
X for (i = 0; result[i]; i++)
X free (result[i]);
X free (result);
X }
X return (char **)NULL;
X }
X
X strcpy (filename, pathname + i);
X strncpy (directory_name, pathname, i);
X directory_name[i] = '\0';
X
X /* If directory_name contains globbing characters, then we have
X to expand the previous levels. Just recurse. */
X
X if (glob_pattern_p (directory_name))
X {
X char **directories;
X
X if (directory_name[i - 1] == '/')
X directory_name[i - 1] = '\0';
X
X directories = glob_filename (directory_name);
X
X if (directories == (char **)NULL) goto memory_error;
X if ((directories == (char **)-1) || !(*directories))
X return (directories);
X
X /* We have successfully globbed the preceding directory name.
X For each name in DIRECTORIES, call glob_vector on it and
X FILENAME. Concatenate the results together. */
X for (i = 0; directories[i]; i++)
X {
X char **temp_results = glob_vector (filename, directories[i]);
X /* Handle error cases ... */
X if (!temp_results) goto memory_error;
X if (temp_results == (char **)-1)
X {
X /* This filename is probably not a directory. Ignore it. */
X }
X else
X {
X char **array = glob_dir_to_array (directories[i], temp_results);
X register int l = 0;
X
X while (array[l]) l++;
X
X result =
X (char **)realloc (result, (result_size + l) * sizeof (char *));
X for (l = 0; array[l]; l++, result_size++)
X result[result_size - 1] = array[l];
X result[result_size - 1] = (char *)NULL;
X free (array); /* DO NOT FREE THE STRINGS, THOUGH! */
X }
X }
X /* Free the directories. */
X for (i = 0; directories[i]; i++)
X free (directories[i]);
X free (directories);
X }
X else
X {
X /* Otherwise, just return what glob_vector returns appended to
X the directory name. */
X char **temp_results;
X
X if (*directory_name)
X temp_results = glob_vector (filename, directory_name);
X else
X temp_results = glob_vector (filename, CURRENTDIR);
X
X if (!temp_results || ((int)temp_results) == -1)
X return temp_results;
X
X result = glob_dir_to_array (directory_name, temp_results);
X }
X return result;
X}
X
X
X
X#ifdef TEST
X
Xmain (argc, argv)
X int argc;
X char **argv;
X{
X char **value;
X int i, index = 1;
X
X while (index < argc) {
X value = glob_filename (argv[index]);
X if ((int) value == 0)
X printf ("Memory exhausted.\n");
X else if ((int) value == -1)
X perror (argv[index]);
X else
X for (i = 0; value[i]; i++)
X printf ("%s\n", value[i]);
X index++;
X }
X return 0;
X}
X
X#endif /* TEST */
SHAR_EOF
echo "End of archive 1 (of 3)"
# if you want to concatenate archives, remove anything after this line
exit